package com.coder4j.platform;

import com.coder4j.platform.entity.AuthApiEntity;
import com.coder4j.platform.service.AuthApiService;
import com.coder4j.platform.cache.*;
import com.coder4j.starter.web.util.ApplicationContextProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author keller
 * @date 2025-04-28 09:55:35
 * 应用启动后运行的内容：
 * 1. 扫描API，进行注册
 * 2. 初始化组织、角色、权限等缓存
 */
@Component
@Slf4j
public class BaseAppRunner implements ApplicationRunner {
    @Value("${spring.application.name}")
    private String appName;

    @Resource
    private AuthApiService authApiService;

    /**
     * 项目启动时，将API添加到数据库中
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {


        new Thread(()->{
            try {
                //等待 SpringContextUtils 生效
                Thread.sleep(10000L);
                ApplicationContext context = ApplicationContextProvider.getApplicationContext();
                String[] beanNamesForAnnotation = context.getBeanNamesForAnnotation(RestController.class);

                Set<Class<?>> classes = new HashSet<>();
                for (String beanName : beanNamesForAnnotation) {
                    Object bean = context.getBean(beanName);
                    //拿到的是代理对象
                    classes.add(AopUtils.getTargetClass(bean));
                }

                // 扫描平台api
                List<AuthApiEntity> apiList = ApiUtils.getApiList(appName,classes);

                //更新API
                authApiService.batchSaveWithDelete(apiList);

                ApiCache.initCache();

                ButtonCache.initCache();

                OrganizationCache.initCache();

                RoleCache.initCache();

                RoleCache.initRoleApiCache();

                DictCache.initCache();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();


    }
}
